﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Cryptography;
using System.Web;
using carShop.Data.EntityFramework;
using carShop.Data.Helpers;

namespace carShop.Data.Repositories
{
    //make all methods to be virtual so that it can be overidable to the classes that will inherit this base class
    public class Repository<T>: IRepository<T> where T:class 
    {
        public CarShopDbContext dbContext { get; set; }
        public DbSet<T> dbSet { get; set; }
        public Repository(CarShopDbContext _dbContext)
        {
            dbContext = _dbContext;
            dbSet = _dbContext.Set<T>();

        }
        public virtual IEnumerable<T> Get()
        {
            return dbSet;
        }

        public virtual IEnumerable<T> GetWithIncludeProperties(string includeProperties)
        {
            if (includeProperties == null)
            {
                throw new NotImplementedException();
            }
            var prop = includeProperties.Split(new char[] {','}, StringSplitOptions.RemoveEmptyEntries);
            IQueryable<T> query = dbSet;
            foreach (var p in prop)
            {
                query = query.Include(p);
            }
            return query;
        }

        public virtual T GetById(int id)
        {
            return dbSet.Find(id);

        }

        public virtual void Insert(T entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Update(T entity)
        {

            //dbSet.Attach(entity);
            //dbContext.Entry(entity).State = EntityState.Modified;
            dbSet.Add(entity);
            dbContext.ApplyStateChanges();

        }

        public virtual void Delete(int id)
        {
            T toBeDeleted = dbSet.Find(id);
            if (dbContext.Entry(toBeDeleted).State == EntityState.Detached)
            {
                dbSet.Attach(toBeDeleted);
            }
            dbSet.Remove(toBeDeleted);

        }



    }
}